<%@ page import="org.example.DAO.BlogDAO" %>
<%@ page import="org.example.entity.Blog" %>
<%@ page import="org.example.DAO.BlogCommentDAO" %>
<%@ page import="org.example.entity.BlogComment" %>
<%@ page import="org.example.DAO.LikeDAO" %>
<%@ page import="org.example.entity.Like" %>
<%@ page import="org.example.DAO.DBUtil" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.util.List" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    // 获取用户ID（修复类型问题）
    Integer userId = null;
    Object userIdObj = session.getAttribute("userId");
    if (userIdObj instanceof Integer) {
        userId = (Integer) userIdObj;
    } else if (userIdObj instanceof String) {
        try {
            userId = Integer.parseInt((String) userIdObj);
        } catch (NumberFormatException e) {
            // 忽略转换错误
        }
    }

    // 获取博客ID
    String blogId = request.getParameter("id");
    if (blogId == null || blogId.isEmpty()) {
        response.sendRedirect("error.jsp?message=博客ID不存在");
        return;
    }

    Connection conn = null;
    Blog blog = null;
    List<BlogComment> comments = null;
    boolean isAuthor = false;
    int[] likeCounts = {0, 0};
    Boolean userLikeStatus = null;
    String contextPath = request.getContextPath();

    try {
        conn = DBUtil.getConnection();
        BlogDAO blogDAO = new BlogDAO(conn);
        BlogCommentDAO commentDAO = new BlogCommentDAO(conn);
        LikeDAO likeDAO = new LikeDAO(conn);

        // 获取博客详情
        blog = blogDAO.getBlogById(blogId);
        if (blog == null) {
            response.sendRedirect("error.jsp?message=博客不存在");
            return;
        }

        // 检查用户是否为作者
        if (userId != null && userId.equals(blog.getUserId())) {
            isAuthor = true;
        }

        // 获取评论列表
        comments = commentDAO.getCommentsByBlogId(blogId);

        // 获取点赞统计
        likeCounts = likeDAO.getBlogLikes(blogId);

        // 获取用户点赞状态
        if (userId != null) {
            userLikeStatus = likeDAO.getUserBlogLikeStatus(userId, blogId);
        }

    } catch (SQLException e) {
        e.printStackTrace();
        response.sendRedirect("error.jsp?message=数据库错误");
        return;
    } finally {
        DBUtil.close(conn);
    }

    // 日期格式化
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
%>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><%=blog.getTitle()%> - 内容评级平台</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-lite.min.css" rel="stylesheet">
    <style>
        :root {
            --primary: #4361ee;
            --secondary: #3f37c9;
            --accent: #4cc9f0;
            --dark: #1d3557;
            --darker: #0d1b2a;
            --light: #f8f9fa;
            --gray: #8d99ae;
            --success: #4caf50;
            --warning: #ff9800;
            --danger: #f44336;
            --card-bg: rgba(29, 53, 87, 0.8);
            --transition: all 0.3s ease;
        }
        body {
            background: linear-gradient(135deg, var(--darker) 0%, var(--dark) 100%);
            color: var(--light);
            min-height: 100vh;
            background-attachment: fixed;
            line-height: 1.6;
        }
        .main-content {
            max-width: 1000px;
            margin: 2rem auto;
            padding: 0 2rem;
        }
        .blog-card {
            background: var(--card-bg);
            border-radius: 15px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }
        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
        }
        .section-title {
            font-size: 1.8rem;
            font-weight: 700;
            position: relative;
            padding-left: 1rem;
        }
        .section-title::before {
            content: "";
            position: absolute;
            left: 0;
            top: 0;
            height: 100%;
            width: 4px;
            background: var(--accent);
            border-radius: 2px;
        }
        .blog-meta {
            color: var(--gray);
            font-size: 0.9rem;
            margin-bottom: 1rem;
            display: flex;
            flex-wrap: wrap;
            gap: 1.5rem;
        }
        .blog-meta span {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        .blog-content {
            background: rgba(255, 255, 255, 0.05);
            border-radius: 10px;
            padding: 1.5rem;
            line-height: 1.8;
            min-height: 200px;
        }
        .blog-actions {
            display: flex;
            gap: 1rem;
            margin-top: 1rem;
        }
        .action-btn {
            display: flex;
            align-items: center;
            gap: 5px;
            color: var(--light);
            background: rgba(255, 255, 255, 0.1);
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 30px;
            cursor: pointer;
            transition: var(--transition);
            text-decoration: none;
            font-size: 0.9rem;
        }
        .action-btn:hover {
            background: rgba(255, 255, 255, 0.2);
        }
        .btn-primary {
            background: var(--primary);
            color: white;
        }
        .btn-primary:hover {
            background: var(--secondary);
        }
        .like-btn {
            display: flex;
            align-items: center;
            gap: 5px;
            padding: 0.5rem 1rem;
            border-radius: 30px;
            cursor: pointer;
            transition: var(--transition);
            font-size: 0.9rem;
            border: none;
            color: darkblue;
        }
        .like-active {
            background: var(--primary);
        }
        .like-btn:hover:not(.like-active) {
            background: rgba(255, 255, 255, 0.2);
        }
        .comment-card {
            background: rgba(255, 255, 255, 0.03);
            border-radius: 10px;
            padding: 1rem;
            margin-bottom: 1rem;
            transition: var(--transition);
        }
        .comment-card:hover {
            background: rgba(255, 255, 255, 0.05);
        }
        .comment-header {
            display: flex;
            align-items: flex-start;
            gap: 1rem;
            margin-bottom: 0.5rem;
        }
        .comment-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: var(--gray);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1rem;
        }
        .comment-info {
            flex: 1;
        }
        .comment-name {
            font-weight: 600;
            color: var(--accent);
        }
        .comment-time {
            font-size: 0.8rem;
            color: var(--gray);
        }
        .comment-content {
            margin-top: 0.5rem;
            line-height: 1.6;
        }
        .comment-actions {
            display: flex;
            gap: 1rem;
            margin-top: 0.5rem;
            font-size: 0.8rem;
        }
        .reply-form {
            margin-top: 1rem;
            padding-left: 50px;
            border-left: 2px solid var(--gray);
        }
        .form-group {
            margin-bottom: 1rem;
        }
        .form-label {
            font-weight: 600;
            margin-bottom: 0.5rem;
            color: var(--accent);
        }
        .form-control {
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            color: var(--light);
            padding: 0.75rem 1rem;
            border-radius: 10px;
        }
        .form-control:focus {
            background: rgba(255, 255, 255, 0.15);
            border-color: var(--accent);
            color: var(--light);
            box-shadow: 0 0 0 0.25rem rgba(76, 201, 240, 0.25);
        }
        .alert-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1000;
            width: 300px;
        }
        .alert {
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
        }
        .empty-state {
            text-align: center;
            padding: 2rem;
            color: var(--gray);
            margin: 1rem 0;
        }
        .empty-state i {
            font-size: 1.5rem;
            margin-bottom: 0.5rem;
            color: var(--accent);
        }
    </style>
</head>
<body>
<!-- 引入公共页头 -->
<jsp:include page="header.jsp" />
<!-- 消息提示容器 -->
<div class="alert-container">
    <div id="alertMessage" class="alert alert-dismissible fade" role="alert">
        <span id="alertText"></span>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
</div>
<div class="main-content">
    <div class="blog-card">
        <div class="section-header">
            <h2 class="section-title"><%=blog.getTitle()%></h2>
            <% if (isAuthor) { %>
            <div class="blog-actions">
                <a href="<%=contextPath%>/blog-edit.jsp?id=<%=blog.getBlogId()%>" class="action-btn"><i class="far fa-edit"></i> 编辑</a>
                <a href="#" class="action-btn text-danger" id="deleteBlog"><i class="far fa-trash-alt"></i> 删除</a>
            </div>
            <% } %>
        </div>
        <div class="blog-meta">
            <span><i class="far fa-user"></i> <%=blog.getUserId()%></span>
            <span><i class="far fa-calendar-alt"></i> <%=dateFormat.format(blog.getCreatedAt())%></span>
            <span><i class="far fa-eye"></i> <%=blog.getViewCount()%> 次浏览</span>
            <span><i class="far fa-comment"></i> <%=comments != null ? comments.size() : 0%> 条评论</span>
            <span><i class="fas fa-thumbs-up"></i> <%=likeCounts[0]%> 赞</span>
            <span><i class="fas fa-thumbs-down"></i> <%=likeCounts[1]%> 踩</span>
            <span>
                <span class="status-dot <%=blog.getStatus() == 1 ? "status-published" : "status-draft"%>"></span>
                <span><%=blog.getStatus() == 1 ? "已发布" : "草稿"%></span>
            </span>
        </div>
        <div class="blog-content" id="blogContent">
            <%=blog.getContent()%>
        </div>
        <div class="blog-actions">
            <button id="likeBtn" class="like-btn <%=userLikeStatus != null && userLikeStatus ? "like-active" : ""%>">
                <i class="fas fa-thumbs-up"></i>
                <span>点赞 <%=likeCounts[0]%></span>
            </button>
            <button id="dislikeBtn" class="like-btn <%=userLikeStatus != null && !userLikeStatus ? "like-active" : ""%>">
                <i class="fas fa-thumbs-down"></i>
                <span>点踩 <%=likeCounts[1]%></span>
            </button>
            <a href="<%=contextPath%>/blog-list.jsp" class="action-btn"><i class="fas fa-list"></i> 查看更多日志</a>
        </div>
    </div>

    <!-- 评论部分 -->
    <div class="blog-card">
        <div class="section-header">
            <h3 class="section-title">评论区</h3>
            <% if (userId != null) { %>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#commentModal">
                <i class="far fa-comment-dots"></i> 发表评论
            </button>
            <% } else { %>
            <a href="<%=contextPath%>/login.jsp" class="action-btn"><i class="far fa-comment-dots"></i> 登录后评论</a>
            <% } %>
        </div>

        <% if (comments != null && !comments.isEmpty()) { %>
        <div class="comments-list">
            <% for (BlogComment comment : comments) { %>
            <div class="comment-card" data-comment-id="<%=comment.getCommentId()%>">
                <div class="comment-header">
                    <div class="comment-avatar">
                        <% if (comment.getAvatar() != null && !comment.getAvatar().isEmpty()) { %>
                        " alt="头像" width="40" height="40" class="rounded-circle">
                        <% } else { %>
                        <i class="fas fa-user"></i>
                        <% } %>
                    </div>
                    <div class="comment-info">
                        <div class="comment-name"><%=comment.getUsername()%></div>
                        <div class="comment-time"><%=dateFormat.format(comment.getCreatedAt())%></div>
                    </div>
                </div>
                <div class="comment-content">
                    <%=comment.getContent()%>
                </div>
                <div class="comment-actions">
                    <button class="reply-btn" data-comment-id="<%=comment.getCommentId()%>">
                        <i class="far fa-reply"></i> 回复
                    </button>
                </div>
                <div class="reply-form" style="display: none;" id="replyForm-<%=comment.getCommentId()%>">
                    <form class="reply-comment-form" data-parent-id="<%=comment.getCommentId()%>">
                        <div class="form-group">
                            <textarea class="form-control" rows="2" placeholder="写下你的回复..." required></textarea>
                        </div>
                        <button type="submit" class="btn btn-primary btn-sm">发表回复</button>
                    </form>
                </div>
            </div>
            <% } %>
        </div>
        <% } else { %>
        <div class="empty-state">
            <i class="far fa-comments"></i>
            <p>暂无评论，快来发表第一条评论吧</p>
        </div>
        <% } %>
    </div>
</div>

<!-- 发表评论模态框 -->
<div class="modal fade" id="commentModal" tabindex="-1" aria-labelledby="commentModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content bg-dark border border-gray-700">
            <div class="modal-header">
                <h5 class="modal-title" id="commentModalLabel">发表评论</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="commentForm">
                    <input type="hidden" id="blogId" name="blogId" value="<%=blog.getBlogId()%>">
                    <input type="hidden" id="parentId" name="parentId" value="">
                    <div class="form-group">
                        <textarea class="form-control" id="commentContent" name="content" rows="5" placeholder="写下你的评论..." required></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" id="submitComment" class="btn btn-primary">发表评论</button>
            </div>
        </div>
    </div>
</div>

<!-- 引入公共页脚 -->
<jsp:include page="footer.jsp" />
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    $(document).ready(function() {
        const ctx = "<%=contextPath%>";
        const blogId = "<%=blog.getBlogId()%>";
        const isAuthor = <%=isAuthor ? "true" : "false"%>;

        // 显示消息函数
        function showAlert(message, type) {
            const alert = $('#alertMessage');
            alert.removeClass('alert-success alert-danger alert-warning');
            switch (type) {
                case 'success': alert.addClass('alert-success'); break;
                case 'danger': alert.addClass('alert-danger'); break;
                case 'warning': alert.addClass('alert-warning'); break;
                default: alert.addClass('alert-info');
            }
            $('#alertText').text(message);
            alert.addClass('show');
            setTimeout(() => alert.removeClass('show'), 5000);
        }

        // 点赞功能
        $('#likeBtn').on('click', function() {
            likeAction(true);
        });

        // 点踩功能
        $('#dislikeBtn').on('click', function() {
            likeAction(false);
        });

        function likeAction(isLike) {
            $.post(ctx + '/blog/like', {
                blogId: blogId,
                type: isLike
            }, function(response) {
                showAlert(response, 'success');

                // 更新点赞数显示
                if (isLike) {
                    const $btn = $('#likeBtn');
                    const currentText = $btn.find('span').text();
                    const currentCount = parseInt(currentText.match(/\d+/)[0]);

                    if (response.includes("取消")) {
                        $btn.removeClass('like-active');
                        $btn.find('span').text('点赞 ' + (currentCount - 1));
                    } else {
                        $btn.addClass('like-active');
                        $btn.find('span').text('点赞 ' + (currentCount + 1));
                        $('#dislikeBtn').removeClass('like-active');
                    }
                } else {
                    const $btn = $('#dislikeBtn');
                    const currentText = $btn.find('span').text();
                    const currentCount = parseInt(currentText.match(/\d+/)[0]);

                    if (response.includes("取消")) {
                        $btn.removeClass('like-active');
                        $btn.find('span').text('点踩 ' + (currentCount - 1));
                    } else {
                        $btn.addClass('like-active');
                        $btn.find('span').text('点踩 ' + (currentCount + 1));
                        $('#likeBtn').removeClass('like-active');
                    }
                }
            }).fail(function(xhr) {
                showAlert('操作失败: ' + xhr.responseText, 'danger');
            });
        }

        // 回复按钮事件
        $('.reply-btn').on('click', function() {
            const commentId = $(this).data('commentId');
            $('#replyForm-' + commentId).toggle();
            // 滚动到回复框
            $('#replyForm-' + commentId).find('textarea').focus();
        });

        // 回复表单提交
        $('.reply-comment-form').on('submit', function(e) {
            e.preventDefault();
            const $form = $(this);
            const parentId = $form.data('parentId');
            const content = $form.find('textarea').val().trim();

            if (!content) {
                showAlert('回复内容不能为空', 'warning');
                return;
            }

            $.post(ctx + '/blog/comment/add', {
                blogId: blogId,
                content: content,
                parentId: parentId
            }, function(response) {
                if (response === "评论成功") {
                    showAlert('回复成功', 'success');
                    // 隐藏回复框并清空内容
                    $form.find('textarea').val('');
                    $form.hide();
                    // 刷新评论区
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showAlert('回复失败: ' + response, 'danger');
                }
            }).fail(function(xhr) {
                showAlert('服务器错误: ' + xhr.status + ' ' + xhr.statusText, 'danger');
            });
        });

        // 发表评论
        $('#submitComment').on('click', function() {
            const content = $('#commentContent').val().trim();
            const parentId = $('#parentId').val();

            if (!content) {
                showAlert('评论内容不能为空', 'warning');
                return;
            }

            $.post(ctx + '/blog/comment/add', {
                blogId: blogId,
                content: content,
                parentId: parentId
            }, function(response) {
                if (response === "评论成功") {
                    showAlert('评论成功', 'success');
                    $('#commentModal').modal('hide');
                    $('#commentContent').val('');
                    // 刷新评论区
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showAlert('评论失败: ' + response, 'danger');
                }
            }).fail(function(xhr) {
                showAlert('服务器错误: ' + xhr.status + ' ' + xhr.statusText, 'danger');
            });
        });

        // 删除博客
        $('#deleteBlog').on('click', function(e) {
            e.preventDefault();
            if (confirm('确定要删除这篇博客吗？此操作不可恢复。')) {
                $.post(ctx + '/blog/delete', {
                    blogId: blogId
                }, function(response) {
                    if (response === "删除成功") {
                        showAlert('博客删除成功', 'success');
                        setTimeout(() => {
                            window.location.href = ctx + '/blog-list.jsp';
                        }, 1500);
                    } else {
                        showAlert('删除失败: ' + response, 'danger');
                    }
                }).fail(function(xhr) {
                    showAlert('服务器错误: ' + xhr.responseText, 'danger');
                });
            }
        });
    });
</script>
</body>
</html>